package org.yelongframework.poi;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.yelongframework.commons.io.IOUtil;

/**
 * 工作薄工具类
 * 
 * @since 1.0.0
 */
public final class WorkbookUtils {

	public WorkbookUtils() {
	}

	public static Workbook build(String fileName) throws IOException {
		String extension = FilenameUtils.getExtension(fileName);
		FileInputStream fileInputStream = new FileInputStream(fileName);
		Workbook workBook;
		if ("xls".equalsIgnoreCase(extension)) {
			workBook = buildByXls(fileInputStream);
		} else if ("xlsx".equalsIgnoreCase(extension)) {
			workBook = buildByXlsx(fileInputStream);
		} else {
			IOUtil.closeQuietly(fileInputStream);
			throw new UnsupportedOperationException("无法根据文件类型创建工作薄" + extension);
		}
		IOUtil.closeQuietly(fileInputStream);
		return workBook;
	}

	public static Workbook buildByFileType(InputStream inputStream, String fileType) throws IOException {
		if ("xls".equals(fileType)) {
			return buildByXls(inputStream);
		} else if ("xlsx".equals(fileType)) {
			return buildByXlsx(inputStream);
		} else {
			throw new IllegalArgumentException("不支持的文件类型：" + fileType);
		}
	}

	public static Workbook buildByXlsx(InputStream inputStream) throws IOException {
		return new XSSFWorkbook(inputStream);
	}

	public static Workbook buildByXls(InputStream inputStream) throws IOException {
		POIFSFileSystem fileSystem = new POIFSFileSystem(inputStream);
		return new HSSFWorkbook(fileSystem);
	}

}
